package hust.iamk.lock;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.NoSuchPaddingException;

import com.cooliris.media.GridLayer;
import com.cooliris.media.LocalDataSource;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class UnlockFileFromPath extends AsyncTask<String, String, String> {
	
	ProgressDialog pdLockFile;

	Context mContext;
	GridLayer mGridLayer;
	ArrayList<String> arrFilePath;
	
	public UnlockFileFromPath(Context mContext, ArrayList<String> arrFilePath,GridLayer mGridLayer) {
		// TODO Auto-generated constructor stub
		this.arrFilePath = arrFilePath;
		this.mContext = mContext;
		this.mGridLayer = mGridLayer;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		pdLockFile = new ProgressDialog(mContext);
		pdLockFile.setMessage("Unlocking file. Please wait...");
		pdLockFile.setIndeterminate(false);
		pdLockFile.setMax(arrFilePath.size());
		pdLockFile.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pdLockFile.setCancelable(false);
		pdLockFile.show();
	}

	/**
	 * Lock file in background thread
	 * */
	@Override
	protected String doInBackground(String... mItem) {
		for(int i = 0; i < arrFilePath.size(); i++){
			try {
				SecurityFileUtils.decrypt(arrFilePath.get(i), LocalDataSource.LOCK_BUCKET_NAME);
				publishProgress(String.valueOf(i));
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        return null;
	}
	
	/**
	 * Updating progress bar
	 * */
	protected void onProgressUpdate(String... progress) {
		// setting progress percentage
		pdLockFile.setProgress(Integer.parseInt(progress[0]));
   }

	@Override
	protected void onPostExecute(String mItem) {
		pdLockFile.dismiss();
		
		// Update grid
		mGridLayer.deselectAll();
	}
}


